import { ElMessage } from 'element-plus';
import type Node from 'element-plus/es/components/tree/src/model/node';
import type { DragEvents } from 'element-plus/es/components/tree/src/model/useDragNode';
import type { NodeDropType } from 'element-plus/es/components/tree/src/tree.type';
import { getResourceCategoryTree, updateOrderResourceCategory } from '@/api/resource';
import { useRequest } from '@jl/common/composable';

export function useTree() {
  const dragStart = ref(false);
  const allowDrag = (draggingNode: any) => {
    // 预制不可拖拽
    return draggingNode.data.isLocked !== 1;
  };
  // 节点开始拖拽时触发的事件
  const handleDragStart = (node: Node, ev: DragEvents) => {
    dragStart.value = true;
    return false;
  };
  // 拖拽进入其他节点时触发的事件
  const handleDragEnter = (draggingNode: Node, dropNode: Node, ev: DragEvents) => {
    // console.log('===>进入其他节点时:', draggingNode);
  };
  // 拖拽离开某个节点时触发的事件
  const LeaveNodeArr = ref([]);
  const handleDragLeave = (draggingNode: Node, dropNode: Node, ev: DragEvents) => {
    // if (!LeaveNodeArr.value.some((item) => item.label === dropNode.label)) {
    //   LeaveNodeArr.value.push(dropNode);
    // }
    // console.log('===>离开某个节点时:', dropNode.label, LeaveNodeArr.value[1]);
  };
  // 在拖拽节点时触发的事件
  const handleDragOver = (draggingNode: Node, dropNode: Node, ev: DragEvents) => {
    // console.log('在拖拽节点时触发:', dropNode.label);
  };
  // 拖拽结束时（可能未成功）触发的事件
  const handleDragEnd = (
    draggingNode: Node,
    dropNode: Node,
    dropType: NodeDropType,
    ev: DragEvents
  ) => {
    // console.log('拖拽结束时:', draggingNode, dropNode, dropType);
  };
  const params = ref<any>({
    CategoryIds: [],
    FromCategoryId: [],
    ToCategoryId: [],
  });
  const mobileSuccessfulFlag = ref(false);
  // 拖拽成功完成时触发的事件
  const handleDrop = async (
    draggingNode: Node,
    dropNode: Node,
    dropType: NodeDropType,
    ev: DragEvents
  ) => {
    console.log(
      '移动的资源分类id:',
      draggingNode.data.categoryName,
      '目标位置:',
      dropNode.data.categoryName,
      '标识：',
      dropType,
      '移动的资源分类parentId:',
      draggingNode.data.parentId,
      '目标位置parentId:',
      dropNode.parent.data.categoryName
    );
    // console.log(
    //   draggingNode.data.categoryId,
    //   LeaveNodeArr.value[1].data.categoryId,
    //   dropNode.data.categoryId
    // );
    // const fData = new FormData();
    // fData.set('CategoryIds', [draggingNode.data.categoryId]);
    // fData.set('FromCategoryId', [LeaveNodeArr.value[1].data.categoryId]);
    // fData.set('ToCategoryId', [dropNode.data.categoryId]);
    // updateOrderResourceCategory({ data: fData }).then((res: any) => {
    //   console.log(res);
    // });
    if (dropType === 'none') {
      mobileSuccessfulFlag.value = false;
    } else {
      mobileSuccessfulFlag.value = true;
    }
    dragStart.value = false;
    return false;
  };

  const categoryTreeData = ref<any>([]);
  // 分类 tree
  const { run: getResourceCategoryTreeRun, data: getResourceCategoryTreeData } = useRequest<
    any,
    any
  >(getResourceCategoryTree, {});

  // 生成分类tree
  const generateCategoryTree = (pid: string, arr: any[], level: number) => {
    const array: any[] = [];
    const level_num = level;
    arr.forEach((item) => {
      if (item.parentId === pid) {
        item.children = generateCategoryTree(item.categoryId, arr, level_num + 1); // 接收子节点
        array.push({ ...item, level: level_num });
      }
    });
    return array;
  };
  const getList = async () => {
    await getResourceCategoryTreeRun();
    const { list } = getResourceCategoryTreeData.value;
    categoryTreeData.value = generateCategoryTree('-1', list, 1);
  };

  onMounted(async () => {
    // 分类列表获取
    getList();
  });

  return {
    handleDragStart,
    handleDragEnter,
    handleDragLeave,
    handleDragOver,
    handleDragEnd,
    handleDrop,
    allowDrag,
    getList,
    categoryTreeData,
    mobileSuccessfulFlag,
    dragStart,
  };
}
